package scenetracer.core;

import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;

import javax.imageio.ImageIO;

import scenetracer.image.Color;
import scenetracer.math.Point2;

public class Texture {

	private Color[][] colors;
	private int width;
	private int height;


	public Texture(String fileName) {
		File f = new File(fileName);
		BufferedImage bi=null;
		
		try {
			bi = ImageIO.read(f);
		} catch (IOException e) {
			System.out.println("Texture "+fileName+" not found.");
			System.exit(1);
		}

		this.width = bi.getWidth();
		this.height = bi.getHeight();
		
		this.colors = new Color[this.height][this.width];
		
		for (int i = 0; i < this.height; i++) {
			for (int j = 0; j < this.width; j++) {
				colors[i][j] = new Color(bi.getRGB(j,i));
			}
		}
	}
	
	public int getWidth() {
		return this.width;
	}

	public int getHeight() {
		return this.height;
	}
	
	public Color getColorAt(Point2 point2) {
		int textureX = (int) (Math.abs((long)Math.round(point2.x * this.width)) 
			% this.width); 
		int textureY = (int) (Math.abs((long)Math.round(point2.y * this.height)) 
			% this.height);
		
		return colors[textureY][textureX];
	}

	

}
